<?php
namespace Home\Controller;
use Think\Controller;
use Think\Controller\RestController;
use Home\Common\Response;
use Home\Common\BizCode;
use Home\Common\ChuanglanSmsApi;
class UserController extends RestController {

    static $msg = ' 您好，您的验证码为';
    public function login(){
        $response = new Response();
        $condition['phone'] = I('param.phone');
        $condition['pwd'] = I('param.pwd');
        $condition['status'] = '0';
        // var_dump($condition);
        if(empty($condition['phone']) || empty($condition['pwd'])){
          unset($condition);
          $condition['token'] = I('token');
        } else {
          $condition['pwd'] = md5($condition['pwd']);
        }
        $Dao = M('User');
        $user = $Dao->where($condition)->find();
        if($user){
          // 登录成功
          // 设置新token
          $user['token'] = md5(uniqid(rand()));
          $Dao->save($user);
          unset($user['pwd']);
          $response->addData('user', $user);
          session('user', $user);
        } else {
          $response->setFailState('USER_LOGIN_FAIL');
        }
        $this->response($response, 'json');
    }

    // 获取验证码 ? type: 0: 注册，1：忘记密码
    public function getCode(){
      $response = new Response();
      $data['phone'] = I('phone');
      $type = I('type');
      if(is_null($data['phone'])){
        $response->setFailState('PARAM_INVALID');
        $this->response($response, 'json');
        exit;
      }

      $Dao = M('User');
      $user = $Dao->where($data)->find();
      if($user && $type == '0'){
        // 注册，用户存在
        $response->setFailState('USER_PHONE_EXISTED');
        $this->response($response, 'json');
        exit;
      }

      if(!$user && $type == "1"){
          // 忘记密码，手机不存在
          $response->setFailState('USER_PHONE_NOT_EXIST');
          $this->response($response, 'json');
          exit;
      }

      // 返回验证码，
      $api = new ChuanglanSmsApi();
      $code = rand(1000, 9999);
      $realmsg = self::$msg.$code;
      $result = $api->sendSMS($data['phone'], $realmsg);
      $result = $api->execResult($result);
      if($result[1] != 0){
        $response->setFailState('USER_CODE_SEND_ERROR');
      }else{
        session('phone_code', $data['phone'].'_'.$code);
      }

      $this->response($response, 'json');
    }

    // 检查验证码
    public function checkCode(){
      $code = I('code');
      $response = new Response();

      $session_code = session('phone_code');
      if(empty($session_code) || end(explode('_', $session_code)) != $code){
        $response->setFailState('USER_CODE_CHECK_FAIL');
        session('check_code', false);
      } else {
        session('check_code', true);
      }
      $this->response($response, 'json');
    }

    public function getSession(){
      $response = new Response();

      $response->addData('session', $_SESSION);
      $this->response($response, 'json');
    }

    // 设置密码
    public function setPwd()
    {
      $response = new Response();
      $data['pwd'] = I('pwd');
      $check_code = session('check_code');
      $session_code = session('phone_code');
      $data['phone'] = current(explode('_', $session_code));
      // var_dump($data);
      // 是否已经验证code
      if(empty($data['pwd']) || !$check_code){
        $response->setFailState('USER_SET_PWD_FAIL');
      } else {
        $data['pwd'] = md5($data['pwd']);
        $Dao = M('User');

        $user = $Dao->where('phone = "%s"', $data['phone'])->find();
        if($user){
          // 用户存在，更新其密码
          $r = $Dao->where('phone = "%s"', $data['phone'])->setField('pwd', $data['pwd']);
          if(!$r){
            $response->setFailState('USER_SET_PWD_FAIL');
          }
        } else {
          // 不存在则添加
          $data['name'] = '用户'.substr($data['phone'], 7);
          $user = $Dao->add($data);
        }
        session(null);
      }
      // $response->addData('data', $data);

      $this->response($response, 'json');
    }

    public function logout()
    {
      session(null);
      $this->response(new Response(), 'json');
    }

    // 修改密码
    public function setNewpwd()
    {
      $response = new Response();
      $user = session('user');
      if(!$user){
        $response->setFailState('UN_LOGIN');
      } else {
        $condition['pwd'] = I('oldpwd');
        $newpwd = I('newpwd');
        if(empty($condition['pwd']) || empty($newpwd)){
          $response->setFailState('PARAM_INVALID');
        } else {
          $condition['pwd'] = md5($condition['pwd']);
          $Dao = M('user');
          $result = $Dao->where('user_id='.$user['user_id'])->field('pwd')->find();
          if($result['pwd'] != $condition['pwd']){
            $response->setFailState('USER_OLDPWD_ERROR');
          } else {
            // 更新数据库
            $Dao->where('user_id='.$user['user_id'])->setField('pwd', md5($newpwd));
          }
        }
      }

      $this->response($response, 'json');
    }

    // 模板
    public function checklogin($value='')
    {
      $response = new Response();
      $user = session('user');
      if(!$user){
        $response->setFailState('UN_LOGIN');
      }
      $this->response($response, 'json');
    }

    // 设置昵称
    public function setName()
    {
      $response = new Response();
      $user = session('user');
      if(!$user){
        $response->setFailState('UN_LOGIN');
      } else {
        $name = I('name');
        if(empty($name)){
          $response->setFailState('PARAM_INVALID');
        } else {
          $Dao = M('user');
          $Dao->where('user_id='.$user['user_id'])->setField('name', $name);
        }
      }

      $this->response($response, 'json');
    }

    public function getDetail()
    {
      $response = new Response();
      $user = session('user');
      if(!$user){
        $response->setFailState('UN_LOGIN');
      } else {
        $response->addData('user', $user);
      }

      $this->response($response, 'json');
    }

    public function addFeedback(){
      $response = new Response();
      $user = session('user');
       if(!$user){
         $response->setFailState('UN_LOGIN');
       } else {
          $data['feedback_content'] = I('content');
          $data['user_id'] = $user['user_id'];
          M('feedback')->add($data);
       }
      $this->response($response, 'json');
    }

    public function setHeadimg() {
      $response = new Response();

      $this->user = session('user');

      if (!$this->user) {
          $response->setFailState('UN_LOGIN');
          $response->addData('user', $this->user);
          $this->response($response, 'json');
          exit;
      }

      $savePath = 'headimg';
      $realPath = __ROOT__ . '/Public/upload/' . $savePath . '/';

      //如果目录不存在，创建目录
      if (!file_exists(DOC_ROOT . '/Public/upload/' . $savePath . '/')) {
          mkdir(DOC_ROOT . '/Public/upload/' . $savePath . '/');
      }

      $config = array(
          'rootPath' => DOC_ROOT . '/Public/upload/',
          'savePath' => '/' . $savePath . '/',
          'saveName' => array('uniqid', ''),
          'exts' => array('jpg', 'gif', 'png', 'jpeg'),
          'autoSub' => false,
          'subName' => array('date', 'Ymd'),
      );
      $upload = new \Think\Upload($config);// 实例化上传类

      // 上传文件
      $info = $upload->upload();
      if (!$info) {// 上传错误提示错误信息
          $response->setFailState('IMG_UPLOAD_ERROR');
      } else {// 上传成功
          // echo json_encode($info['file']);
          $file = $info[0];
          $data['headimg'] = $realPath.$file['savename'];
          $data['user_id'] = $this->user['user_id'];

          M('user')->save($data);
      }

      // $response->addData('info', I('param.'));
      $this->response($response, 'json');
    }

}
